package com.ykq.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ykq.util.CommonResult;
import com.ykq.util.MyUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.PrintWriter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @program: tui-education
 * @description:
 * @author: 闫克起2
 * @create: 2022-04-13 09:08
 **/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;//密码加密器
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Bean //创建一个密码加密器的对象交于spring容器来管理
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();//禁用跨域伪造请求
        http.formLogin()
                .successHandler(successHandler())//登录成功的处理器
                .failureHandler(failureHandler()) //登录失败的处理器
                .loginProcessingUrl("/sso/login")
                .permitAll();//允许放行

        http.cors(); //允许跨域请求

        http.authorizeRequests().anyRequest().authenticated();//其他的请求都需要认证通过后才能访问
    }

    //登录成功的处理方法
    private AuthenticationSuccessHandler successHandler() {
        return (request, response, authentication) -> {
            response.setContentType("json/application;charset=utf-8");
            PrintWriter writer = response.getWriter();
            ObjectMapper objectMapper=new ObjectMapper();
            MyUserDetails principal = (MyUserDetails) authentication.getPrincipal(); //认证的用户信息
            String id = principal.getId();//用户id
            String username = principal.getUsername();//用户名

            Collection<? extends GrantedAuthority> authorities = principal.getAuthorities();

            List<String> collect = authorities.stream().map(item -> item.getAuthority()).collect(Collectors.toList());
            //生成token.
            Date nowDate=new Date();
            Calendar calendar=Calendar.getInstance();
            calendar.set(Calendar.SECOND,7200);
            Date expire = calendar.getTime(); //过期时间
            Map<String,Object> head=new HashMap<>();
            head.put("alg","HS256");
            head.put("typ","JWT");
            String token = JWT.create()
                    .withHeader(head)
                    .withIssuedAt(nowDate)
                    .withExpiresAt(expire)
                    .withClaim("username", username) //你把用户的什么信息存放token中 存入用户名
                    .withClaim("auths", collect)   //存入用户的权限
                    .withClaim("userid",id)
                    .sign(Algorithm.HMAC256("ykq-AAA"));//加密方式

            redisTemplate.opsForValue().set(token,"",24*60*60, TimeUnit.SECONDS);

            CommonResult result=new CommonResult(2000,"登录成功",token);
            String value = objectMapper.writeValueAsString(result);
            writer.print(value);

            writer.flush();
            writer.close();

        };
    }

    //登录失败
    private AuthenticationFailureHandler failureHandler() {
        return (request, response, exception) -> {
            response.setContentType("json/application;charset=utf-8");
            PrintWriter writer = response.getWriter();
            ObjectMapper objectMapper=new ObjectMapper();
            CommonResult commonResult=new CommonResult(5001,"登录失败",null);
            String value = objectMapper.writeValueAsString(commonResult);

            writer.print(value);

            writer.flush();
            writer.close();
        };
    }

}





























